package com.hotai.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotai.comment.dtos.CellValue;
import com.hotai.comment.dtos.PageResponseResult;
import com.hotai.comment.dtos.ResponseResult;
import com.hotai.comment.enums.AppHttpCodeEnum;
import com.hotai.comment.enums.AppJwtUtil;
import com.hotai.comment.md5.MD5Utils;
import com.hotai.comment.pojo.*;
import com.hotai.comment.yanzheng.SMS;
import com.hotai.comment.yanzheng.TestCode;
import com.hotai.comment.yanzheng.TestCodeInforVo;
import com.hotai.mapper.EquipmentMapper;
import com.hotai.mapper.InstitutionMapper;
import com.hotai.mapper.LoginLogMapper;
import com.hotai.mapper.UserStudentMapper;
import com.hotai.service.UserStudentSerivice;
import com.hotai.vo.equipment.EquipmentList;
import com.hotai.vo.she.SheBao;
import com.hotai.vo.user.Deng;
import com.hotai.vo.user.LoginDto;
import com.hotai.vo.user.LoginZhu;
import com.hotai.vo.userteacher.StuXiuGai;
import com.hotai.vo.userteacher.TeaXiuGai;
import com.hotai.vo.userteacher.UserTeacherJin;
import com.hotai.vo.usestudent.*;
import io.jsonwebtoken.Claims;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserStudentSeriviceImpl extends ServiceImpl<UserStudentMapper, UserStudent> implements UserStudentSerivice {

    @Autowired
    private UserStudentMapper userStudentMapper;


    @Autowired
    private InstitutionMapper institutionMapper;

//    @Autowired
//    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private LoginLogMapper loginLogMapper;


    private static final String Salt = "MHCDEKLDE321";


    @Override
    public ResponseResult UserStudentPage(UserStudentList query) {
        //参数为空
        if (query == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        query.checkParam();
        PageHelper.startPage(query.getPage(), 20);
        ArrayList<UserStudentListPage> detaile = userStudentMapper.UserStudentPage(query);
        for (UserStudentListPage userStudentListPage : detaile) {
            if (userStudentListPage.getType() == 2) {
                userStudentListPage.setIname("个人");
            }
        }
        PageInfo<UserStudentListPage> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(query.getPage(), pageInfo.getSize(), (int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        return responseResult;
    }

    @Override
    public ResponseResult UserStudentdetail(UserStudentdetaile queryware) {
        //参数为空
        if (queryware == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        queryware.checkParam();
        if (queryware.getXueid() == null) {
            queryware.setXueid(1);
        }
        queryware.setPage((queryware.getPage() - 1) * queryware.getSize());

        if (queryware.getXueid() == 1) {
            ArrayList<UserStudentDetailePage> detaile = userStudentMapper.detaile(queryware);
            PageResponseResult responseResult = new PageResponseResult(queryware.getPage() + 1, queryware.getSize(), detaile.size());
            responseResult.setData(detaile);
            return responseResult;
        } else if (queryware.getXueid() == 2) {
            //天数
            Integer tian = userStudentMapper.tianDate(Integer.toString(queryware.getId()));

            UserStudentDetaliXue detaliXue = new UserStudentDetaliXue();

            UserStudentDetaliXue detaile = userStudentMapper.detaileXueid(queryware);

            if (detaile != null) {
                BeanUtils.copyProperties(detaile, detaliXue);
            }
            detaliXue.setTian(tian);
            return ResponseResult.okResult(detaliXue);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());

    }

    @Override
    public ResponseResult UserStudentChong(Integer id) {
        String passwrod = MD5Utils.encodeWithSalt("000000", Salt);
        try {
            userStudentMapper.chongzhi(id, passwrod);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult UserStudentXuedetail(UserStudentXUedetaile queryware) {
        //参数为空
        if (queryware == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        queryware.checkParam();
        PageHelper.startPage(queryware.getPage(), 20);
        if (queryware.getDa() == null) {
            queryware.setDa(30);
        }
        ArrayList<StudentCourseware> detaile = userStudentMapper.Xuedetaile(queryware);
        PageInfo<StudentCourseware> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(queryware.getPage(), pageInfo.getSize(), (int) pageInfo.getTotal());
        responseResult.setData(detaile);
        return responseResult;
    }


    @Override
    public ResponseResult UserSheChong(SheChon sheChon) {
        String sysCode = redisTemplate.opsForValue().get(sheChon.getPhone());//提取系统的验证码
        if (sysCode == null) {
            return ResponseResult.errorResult(505, "验证码未发送或已过期");
        }
        if (!sysCode.equals(sheChon.getCode())) {
            return ResponseResult.errorResult(505, "验证码不正确");
        }

        //手机号是否存在
        UserStudent userStudentPage = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, sheChon.getPhone()));
        if (userStudentPage == null) {
            return ResponseResult.errorResult(506, "手机号尚未注册");
        }
        //判断密是否一致
        if (!sheChon.getPassword().equals(sheChon.getPassword2())) {
            return ResponseResult.errorResult(507, "密码不一致");
        }
        sheChon.setPassword(MD5Utils.encodeWithSalt(sheChon.getPassword(), Salt));
        try {
            userStudentMapper.SheXiu(sheChon);
            redisTemplate.delete(sheChon.getPhone());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult UpdateSheXian(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        userStudentMapper.XianZhi(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    public List<String> dayList() {

        ArrayList<String> arrayList = new ArrayList<>();
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Date today = new Date();
        String endDate = sdf.format(today); //当前日期
        //获取三十天前日期
        for (int i = 30; i >= 0; i--) {
            Calendar theCa = Calendar.getInstance();
            theCa.setTime(today);
            theCa.add(theCa.DATE, -i); //最后一个数字30可改，30天的意思
            Date start = theCa.getTime();
            String startDate = sdf.format(start); //三十天之前日期
            arrayList.add(startDate);
        }
        return arrayList;
    }


    @Override
    public ResponseResult UserStudentXueCount(Integer id) {

        //从数据库中查询指定天数之前到当前每天的订单数
        List<Map<String, Object>> orders = userStudentMapper.XueCount(id);
//补全数据库中不存在的日期，订单数为0

        List<String> dayList = dayList();
        boolean exists = false;
        for (int i = 0; i < dayList.size(); i++) {
            exists = false;
            for (Map<String, Object> hs : orders) {
                if (dayList.get(i).equals(hs.get("shoDate"))) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                final String date2 = dayList.get(i);
                orders.add(i, new HashMap<String, Object>() {{
                    put("count", 0);
                    put("shoDate", date2);
                }});
            }
        }
        return ResponseResult.okResult(orders);
    }


    @Override
    public ResponseResult UserStudentAdd(UserStudentImporAdd userStudentAdd) {
        if (userStudentAdd.getUserStudentAdd().size() <= 0) {
            throw new RuntimeException("没有数据");
        }
        ArrayList<UserStudentImpl> userStudentAdd1 = userStudentAdd.getUserStudentAdd();
        for (UserStudentImpl userStudentA : userStudentAdd1) {
            UserStudent userStudent = new UserStudent();
            //手机号是否存在
            UserStudent userStudentPage = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, userStudentA.getPhone()));
            if (userStudentPage != null) {
                throw new RuntimeException("手机号重复");
            }
            //用户是否存在
            UserStudent userStudentPhone = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getName, userStudentA.getName()));
            if (userStudentPhone != null) {
                throw new RuntimeException("用户名重复");
            }

            if (userStudentA.getIname().equals("个人")) {
                userStudent.setType(2);
            } else {
                Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, userStudentA.getIname()));
                userStudent.setType(1);
                userStudent.setSid(institution.getId());
            }
            userStudent.setPhone(userStudentA.getPhone().toString());
            userStudent.setZhename(userStudentA.getName().toString());
            userStudent.setName(suiji());
            userStudent.setCreateDate(new Date());
            userStudent.setDeid(1);
            userStudent.setPassword(MD5Utils.encodeWithSalt("000000", Salt));
            userStudent.setSalt(Salt);
            userStudent.setStatus(1);
            userStudentMapper.insert(userStudent);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult QuanXian(String ide) {
        String[] split = ide.split(",");
        for (String s : split) {
            userStudentMapper.XianZhi(Integer.parseInt(s));
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult BaoGao(SheBao sheBao) {

        return null;
    }

    @Override
    public ResponseResult UserStudentByid(Integer id) {
        UserStudentAdd userStudentAdd = userStudentMapper.UserStudentByid(id);
        return ResponseResult.okResult(userStudentAdd);
    }

    @Override
    public ResponseResult Palogin(LoginDto dto) {
        if ((StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getCode()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
            UserStudent dbUser = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, dto.getUsername()).eq(UserStudent::getDeid, 1));
            //手机号登录
            UserStudent UserPhone = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, dto.getUsername()).eq(UserStudent::getDeid, 1));
            //手机号登录
            if (UserPhone != null) {
                if (dto.getCode() != null) {
                    //1.校验
                    String sysCode = redisTemplate.opsForValue().get(dto.getUsername());//提取系统的验证码
                    if (sysCode == null) {
                        return ResponseResult.errorResult(507, "验证码未发送或已过期");
                    }
                    if (!sysCode.equals(dto.getCode())) {
                        return ResponseResult.errorResult(505, "验证码不正确");
                    }
                    Map<String, Object> map = new HashMap<>();
                    Deng deng = new Deng();
                    map.put("token", AppJwtUtil.getToken(UserPhone.getId().longValue()));
                    deng.setToken(AppJwtUtil.getToken(UserPhone.getId().longValue()));
                    deng.setId(UserPhone.getId());
                    return ResponseResult.okResult(deng);
                } else {
                    String pswd = MD5Utils.encodeWithSalt(dto.getPassword(), Salt);
                    if (dbUser.getPassword().equals(pswd)) {
                        Map<String, Object> map = new HashMap<>();
                        Deng deng = new Deng();
                        map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
                        deng.setToken(AppJwtUtil.getToken(dbUser.getId().longValue()));
                        deng.setId(dbUser.getId());
                        return ResponseResult.okResult(deng);
                    }
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");

        }
        return null;
    }

    @Override
    public ResponseResult Studentcontact(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        userStudentMapper.contact(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult Studentmultiple(String ide) {
        if (ide == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        String[] split = ide.split(",");
        for (String s : split) {
            userStudentMapper.contact(Integer.parseInt(s));
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult XiuGaiReality(UserStudentAccount userStudentAccount) {
        UserStudent userStudent = userStudentMapper.selectById(userStudentAccount.getId());
        userStudent.setZhename(userStudentAccount.getName());
        userStudentMapper.updateById(userStudent);
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult UserStudentXueSave(UserStudentAdd userStudentAdd) {
        if (userStudentAdd.getId() == null) {
            //赋值
            userStudentAdd.setName(suiname());
            UserStudent userStudent = new UserStudent();
            userStudent.setCreateDate(new Date());
            userStudent.setDeid(1);
            userStudent.setPassword(MD5Utils.encodeWithSalt("000000", Salt));
            userStudent.setSalt(Salt);
            userStudent.setStatus(1);
            userStudent.setImg("https://sheb.oss-cn-beijing.aliyuncs.com/kejian/1658296656575.jpg");
            userStudent.setAd(suiji());
            if (userStudentAdd.getType() == 1) {
                Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, userStudentAdd.getIname()));
                userStudentAdd.setSid(institution.getId());
                userStudentAdd.setName(suiji());
                BeanUtils.copyProperties(userStudentAdd, userStudent);
                userStudentMapper.insert(userStudent);
                return ResponseResult.okResult(userStudent.getName());
            } else if (userStudentAdd.getType() == 2) {
                String sysCode = redisTemplate.opsForValue().get(userStudentAdd.getPhone());//提取系统的验证码
                if (sysCode == null) {
                    return ResponseResult.errorResult(500, "验证码未发送或已过期");
                }
                if (!sysCode.equals(userStudentAdd.getCode())) {
                    return ResponseResult.errorResult(500, "验证码不正确");
                }

                //手机号是否存在
                UserStudent userStudentPage = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, userStudentAdd.getPhone()));
                if (userStudentPage != null) {
                    return ResponseResult.errorResult(500, "手机号重复");
                }
                //用户是否存在
//                UserStudent userStudentPhone = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getName, userStudentAdd.getName()));
//                if (userStudentPhone != null) {
//                    return ResponseResult.errorResult(500, "用户名重复");
//
//                }
                BeanUtils.copyProperties(userStudentAdd, userStudent);
                userStudentMapper.insert(userStudent);
                redisTemplate.delete(userStudentAdd.getPhone());
            }
        } else {
            UserStudent userStudent = new UserStudent();
            if (userStudentAdd.getType() == 1) {
                Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, userStudentAdd.getIname()));
                userStudentAdd.setSid(institution.getId());
                BeanUtils.copyProperties(userStudentAdd, userStudent);
                userStudentMapper.updateById(userStudent);
            } else if (userStudentAdd.getType() == 2) {
                String sysCode = redisTemplate.opsForValue().get(userStudentAdd.getPhone());//提取系统的验证码
                if (sysCode == null) {
                    return ResponseResult.errorResult(500, "验证码未发送或已过期");

                }
                if (!sysCode.equals(userStudentAdd.getCode())) {
                    return ResponseResult.errorResult(500, "验证码不正确");

                }

                //手机号是否存在
                List<UserStudent> userStudentPage = userStudentMapper.selectList(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, userStudentAdd.getPhone()));
                if (userStudentPage.size() > 1) {
                    return ResponseResult.errorResult(500, "手机号重复");

                }
                //用户是否存在
                List<UserStudent> userStudentPhone = userStudentMapper.selectList(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getName, userStudentAdd.getName()));
                if (userStudentPhone.size() > 1) {
                    return ResponseResult.errorResult(500, "用户名重复");

                }
//                userStudent.setAd(suiji());

                BeanUtils.copyProperties(userStudentAdd, userStudent);
                userStudentMapper.updateById(userStudent);
                redisTemplate.delete(userStudentAdd.getPhone());
            }

        }


        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult StugetTestCodeYan(String phone) {
        ResponseResult result = new ResponseResult();
        if (phone == null || phone.length() == 0) {
            result.setCode(403);
            result.setErrorMessage("手机号为空");
            return result;
        }
        String code = TestCode.getCode();
        if (code == null || code.length() == 0) {
            result.setCode(403);
            result.setErrorMessage("无效的验证码");
            return result;
        }

        try {
            SMS.batchsendsm(phone, code);
        } catch (Exception e) {
            result.setCode(503);
            result.setErrorMessage("验证码发送失败");
            return result;
        }
        TestCodeInforVo testCodeInfor = new TestCodeInforVo();
        testCodeInfor.setCode(code);
        testCodeInfor.setPhone(phone);
        testCodeInfor.setDate(System.currentTimeMillis());
        testCodeInforMap.put(phone, testCodeInfor);
        result.setCode(0);
        result.setErrorMessage("验证码发送成功");
        result.setData(code);                    //测试
        return result;
    }

    @Override
    public ResponseResult GuanStuList(EquipmentList query) {
        //参数为空
        if (query == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();
        LambdaQueryWrapper<UserStudent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (query != null) {
            lambdaQueryWrapper.like(StringUtils.isNotBlank(query.getName()), UserStudent::getName, query.getName())
                    .eq(UserStudent::getDeid, 1);
        }
        Page page2 = new Page(query.getPage(), query.getSize());
        IPage page = page(page2, lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(query.getPage(), query.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    @Override
    public ResponseResult AddStudent(UserStudent userStudent) {
        userStudent.setCreateDate(new Date());
        userStudent.setDeid(1);
        userStudent.setPassword("000000");
        userStudent.setUsername(suiji());
        userStudent.setStatus(1);
        userStudentMapper.insert(userStudent);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    private UserStudent userId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claimsBody = AppJwtUtil.getClaimsFromToken(token);//解析token
        UserStudent userStudent = userStudentMapper.selectById(claimsBody.getId());
        if (userStudent != null) {
            return userStudent;
        }
        return null;
    }

    @Override
    public ResponseResult StudentJinBenDetail(Integer id, HttpServletRequest request) {
        if (id == null) {
            UserStudent userStudent = userId(request);
            ArrayList<UserTeacherJin> jinBan = userStudentMapper.StuJinBan(userStudent.getId());
            return ResponseResult.okResult(jinBan);
        } else {
            ArrayList<UserTeacherJin> jinBan = userStudentMapper.StuJinBan(id);
            return ResponseResult.okResult(jinBan);
        }
    }

    @Override
    public ResponseResult XiuGaiTead(StuXiuGai teaXiuGai) {
        if (teaXiuGai.getPassword().equals(teaXiuGai.getPassword2())) {
            String pswd = MD5Utils.encodeWithSalt(teaXiuGai.getPassword(), Salt);
            teaXiuGai.setPassword(pswd);
            userStudentMapper.XIuGai(teaXiuGai);
            return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
    }

    @Override
    public ResponseResult XiuGaiTeadPhone(TeaXiuGai teaXiuGai) {
        String sysCode = redisTemplate.opsForValue().get(teaXiuGai.getPhone());
        if (sysCode == null) {
            return ResponseResult.errorResult(505, "验证码未发送或已过期");
        }
        if (!sysCode.equals(teaXiuGai.getCode())) {
            return ResponseResult.errorResult(505, "验证码不正确");
        }
        //手机号是否存在
        List<UserStudent> userStudentPage = userStudentMapper.selectList(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, teaXiuGai.getPhone()));
        if (userStudentPage.size()>0){
            return ResponseResult.errorResult(505, "手机号重复");
        }
        userStudentMapper.XiuPhone(teaXiuGai);
        redisTemplate.delete(teaXiuGai.getPhone());
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult Daochu(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        try {
            //准备数据
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("学生");
            //课程
            HSSFRow row = sheet.createRow(0);
            int num = 0;
            //创建第一行第一个单元格
            HSSFCell cell = row.createCell(num++);
            cell.setCellValue("用户名");
            cell = row.createCell(num++);
            cell.setCellValue("绑定手机号");
            cell = row.createCell(num++);
            cell.setCellValue("所属机构");
//            cell = row.createCell(num++);
//            cell.setCellValue("操作");
            //下载文件
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
//            response.setHeader("content-disposition",
//                    "attachment;filename=" + java.net.URLEncoder.encode("学生.xls", "UTF-8")
//                            + ";filename*=utf-8''" + java.net.URLEncoder.encode("学生.xls", "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("学生.xls", "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult improtStu(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        try {
            HSSFWorkbook workbook2 = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet2 = workbook2.getSheet("学生");
            int lastRowNum2 = sheet2.getLastRowNum();
            ArrayList<UserStudentImpl> userStudents = new ArrayList<>();
            for (int i = 1; i <= lastRowNum2; i++) {
                UserStudentImpl emp2 = new UserStudentImpl();
                HSSFRow row = sheet2.getRow(i);
                int num = 0;
                HSSFCell cell = row.getCell(num++);
                String name = CellValue.getCellValue(cell);
                String phone = CellValue.getCellValue(row.getCell(num++));
                String iname = CellValue.getCellValue(row.getCell(num++));
                if (!iname.equals("个人")) {
                    Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, iname));
                    if (institution == null) {
                        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前机构不存在");
                    }
                }
                emp2.setName(name);
                emp2.setPhone(phone);
                emp2.setIname(iname);
                emp2.setTime(new Date());
                userStudents.add(emp2);
            }
            return ResponseResult.okResult(userStudents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
    }

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        if ((StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getEqid()==null){
            return  ResponseResult.errorResult(590,"此设备已被限制");
        }else {
            Equipment equipment = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, dto.getEqid()));
                if (equipment==null){
                    return  ResponseResult.errorResult(591,"未能找此设备信息");
                }
            if (equipment.getStatus()==2){
                return  ResponseResult.errorResult(590,"此设备已被限制");
            }
        }
        //2.手机号+密码登录
        if (!StringUtils.isEmpty(dto.getUsername()) && !StringUtils.isEmpty(dto.getPassword())) {
            //用户登录
            UserStudent dbUser = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, dto.getUsername()));
            if (dbUser != null) {
//                String pswd = DigestUtils.md5DigestAsHex((dto.getPassword()+dbUser.getSalt()).getBytes());
                String pswd = MD5Utils.encodeWithSalt(dto.getPassword(), Salt);
                if (dbUser.getStatus() == 2) {
                    return ResponseResult.errorResult(506, "该账号被限制无法登录");
                }
                if (dbUser.getDeid() == 2) {
                    return ResponseResult.errorResult(506, "该账号已被删除");
                }
                if (dbUser.getPassword().equals(pswd)) {
                    Map<String, Object> map = new HashMap<>();
                    Deng deng = new Deng();
                    map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
                    redisTemplate.delete(dbUser.getId().toString());
                    redisTemplate.opsForValue().set(dbUser.getId().toString(), map.get("token").toString(), 7, TimeUnit.DAYS);
//                    dbUser.setPassword("");
//                    dbUser.setSalt("");
                    dbUser.setDengDate(new Date());
                    userStudentMapper.updateById(dbUser);

                    //登录时间
                    LoginLog userActive = new LoginLog();
                    userActive.setStuName(Integer.toString(dbUser.getId()));
                    userActive.setCreatetime(new Date());
                    loginLogMapper.insert(userActive);

                    deng.setToken(map.get("token").toString());
                    deng.setId(dbUser.getId());
                    return ResponseResult.okResult(deng);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getErrorMessage());
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }
        return null;
    }

    @Override
    public ResponseResult zhuCe(LoginZhu loginZhu) {
        //1.校验
        String sysCode = redisTemplate.opsForValue().get(loginZhu.getPhone());//提取系统的验证码
        if (sysCode == null) {
            return ResponseResult.errorResult(505, "验证码未发送或已过期");
        }
        if (!sysCode.equals(loginZhu.getCode())) {
            return ResponseResult.errorResult(505, "验证码不正确");
        }
        UserStudent userStudent = new UserStudent();
        //账号是否存在
//        UserStudent userStudentList = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getName, loginZhu.getName()));
//        if (userStudentList != null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号重复");
//        }
        //手机号是否存在
        UserStudent userStudentPage = userStudentMapper.selectOne(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getPhone, loginZhu.getPhone()));
        if (userStudentPage != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号重复");
        }
        //判断密是否一致
        if (!loginZhu.getPassword().equals(loginZhu.getPassword2())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "密码不一致");
        }
        //对象赋值
        loginZhu.setPassword(MD5Utils.encodeWithSalt(loginZhu.getPassword(), Salt));
        BeanUtils.copyProperties(loginZhu, userStudent);
        userStudent.setName(suiname());
        userStudent.setSalt(Salt);
        userStudent.setCreateDate(new Date());
        userStudent.setDeid(1);
        userStudent.setStatus(1);
        userStudent.setType(2);
        userStudent.setImg("https://sheb.oss-cn-beijing.aliyuncs.com/kejian/1658296656575.jpg");
        userStudent.setAd(suiji());
        userStudentMapper.insert(userStudent);
        //清楚缓存
        redisTemplate.delete(loginZhu.getPhone());
        return ResponseResult.okResult(userStudent.getUsername());
    }

    @Override
    public boolean send(HashMap<String, Object> map, String phone) {
        if (StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI5tARXQGTHyAAfyMzwFfT", "tC93mIUi1FSgvoMvraJbLK90s0aUei");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers", phone); //手机号
        request.putQueryParameter("SignName", "冰镇山竹科技有限公司"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode", "SMS_241900638"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //验证码数据，转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private final static Map<String, TestCodeInforVo> testCodeInforMap = new HashMap<String, TestCodeInforVo>();

    private String suiji() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 10; i++) {
            result += random.nextInt(10);
        }

        return result;
    }

    private String   suiname() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }

        return result;
    }

}
